package cn.xinfei.xdecision.data.alarm;

import cn.xinfei.xdecision.common.model.datax.enums.AlarmTypeEnum;
import com.alibaba.fastjson.JSONObject;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class AlarmManager {

    /**
     * 存上次告警时间 key: 名称 value: 时间戳
     */
    private static Map<String, AtomicLong> threadPoolExecutorAlarmTimeMap = new ConcurrentHashMap<>();

    public static void sendAlarmMessage(AlarmMessage alarmMessage) {
        AtomicLong alarmTime = threadPoolExecutorAlarmTimeMap.get(alarmMessage.getAlarmName());
        if (alarmTime != null && (alarmTime.get() + alarmMessage.getAlarmTimeInterval() * 60 * 1000) > System.currentTimeMillis()) {
            return;
        }

        if (alarmMessage.getAlarmType() == AlarmTypeEnum.DING_TALK) {
            DingDingMessageUtil.sendTextMessage(alarmMessage.getAccessToken(), alarmMessage.getSecret(), alarmMessage.getMessage());
        }
        if (alarmMessage.getAlarmType() == AlarmTypeEnum.EXTERNAL_SYSTEM) {
            JSONObject request = new JSONObject();
            request.fluentPut("alarmName", alarmMessage.getAlarmName());
            request.fluentPut("message", alarmMessage.getMessage());
            DingDingMessageUtil.post(alarmMessage.getApiUrl(), request);
        }
        threadPoolExecutorAlarmTimeMap.put(alarmMessage.getAlarmName(), new AtomicLong(System.currentTimeMillis()));
    }

}
